<template>
  <div>
    <wu-dialog :show.sync="dialogVisible" title="上传图片" @close="close">
      <el-upload
        class="avatar-uploader"
        action="/api/my/upload"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
        :headers="headers"
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </wu-dialog>
  </div>
</template>

<script>
export default {
  name: "upload",
  props: {
    visible: {
      default: false,
    },
  },
  data() {
    return {
      dialogVisible: this.visible,
      imageUrl: "",
      headers: {
        token: localStorage.getItem("token") || "", //携带自己的token
      },
    }
  },
  watch: {
    visible(n) {
      this.dialogVisible = n
    },
    dialogVisible(n) {
      this.$emit("update:visible", n)
    },
  },
  methods: {
    //上传成功之后的回调
    async handleAvatarSuccess(res, file) {
      console.log(res)
      this.imageUrl = res.data
      console.log(this.imageUrl)
      this.$emit("getData", this.imageUrl)
      // 将imgUrl保存数据库里面
      let params = { imgUrl: this.imageUrl }
      await this.$api.my.headImgData(params).then((res) => {
        console.log(res)
        // 更新前端localstoreage中的数据
        let User = JSON.parse(localStorage.getItem("UserShopInfo"))
        let newValue = {
          user_photo: res.data[0].user_photo,
        }
        Object.assign(User.data[0], newValue)
        localStorage.setItem("UserShopInfo", JSON.stringify(User))
      })
      this.dialogVisible = false
      this.$router.push("/my")
    },

    // 上传之前的回调
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || "image/jpeg"
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!")
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!")
      }
      return isJPG && isLt2M
    },
    close() {
      Object.assign(this.$data, this.$options.data())
    },
  },
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
